<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图 -->
    <el-card>

      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
                    v-for="(item1, i1) in scope.row.menus" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeMenuById(scope.row, item1.id)">{{ item1.name }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过 for 循环 嵌套渲染二级权限 -->
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children"
                        :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeMenuById(scope.row, item2.id)">{{ item2.name }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3, i3) in item2.children" :key="item3.id" closable
                            @close="removeMenuById(scope.row, item3.id)">{{ item3.name }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色id" prop="id" v-if="false"></el-table-column>
        <el-table-column label="角色名称" prop="name"></el-table-column>
        <el-table-column label="角色状态" prop="status">
          <template slot-scope="scope">
            <el-switch active-value="启用" inactive-value="禁用" v-model="scope.row.status"
                       @change="roleStatusChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"
                       @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete"
                       @click="deleteRole(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting"
                       @click="setMenu(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 修改角色的对话框 -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色备注">
          <el-input v-model="editForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%">
      <!-- 内容主体区域 -->
      <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addRoleForm.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色备注" prop="remark">
          <el-input v-model="addRoleForm.remark" placeholder="请输入角色备注"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogClosed">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setMenuDialogVisible" width="50%" @close="setMenuDialogClosed">
      <!-- 树形控件 -->
      <el-tree :data="menusList" :props="treeProps" show-checkbox node-key="id" default-expand-all
               :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setMenuDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotMenus">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Role",
  data() {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 控制添加角色对话框的显示与隐藏
      addDialogVisible: false,
      // 添加角色的表单数据
      addRoleForm: {
        name: '',
        remark: ''
      },
      addRoleFormRules: [{
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        remark: [
          { message: '请输入角色备注', trigger: 'blur' },
        ]
      }],
      // 控制修改角色对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的角色信息对象
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        remark: [
          { message: '请输入角色备注', trigger: 'blur' },
        ]
      },
      // 控制分配权限对话框的显示与隐藏
      setMenuDialogVisible: false,
      // 所有权限的数据
      menusList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'name',
        children: 'children'
      },
      // 默认选中的节点Id值数组
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取所有角色的列表
    getRoleList() {
      this.$http.get('/driver/role/list').then(res => {
        if (res.data.code === 200) {
          this.rolesList = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        console.log(err)
        this.$message.error(err.message)
      })
    },

    // 监听添加角色对话框的关闭事件
    addDialogClosed(){
      this.$refs.addRoleFormRef.resetFields()
      this.addDialogVisible = false
    },
    // 添加角色
    addRole(){
      this.$refs.addRoleFormRef.validate(valid => {
        if (!valid) return
        this.$http.post("/driver/role/add", this.addRoleForm).then(res => {
          if (res.data.code === 200){
            this.$message.success(res.data.message)
            this.$refs.addRoleFormRef.resetFields()
            this.addDialogVisible = false
            this.getRoleList()
          }else {
            this.$message.error(res.data.message)
          }
        }).catch(err => {
          console.log(err)
          this.$message.error(err.message)
        })
      })
    },
    // 监听 switch 开关状态的改变
    roleStatusChanged(roleStatus){
      let status
      if (roleStatus.status === '启用') {
        status = '禁用'
      } else if (roleStatus.status === '禁用'){
        status = '启用'
      }
      this.$http.get("/driver/role/change/status", {
        params: {
          roleId: roleStatus.id,
          status: roleStatus.status
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
        } else {
          roleStatus.status = status
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        console.log(err)
        roleStatus.status = status
        this.$message.error(err.message)
      })
    },
    // 删除角色的权限
    removeMenuById(role, menuId) {
      this.$confirm('确定删除该角色的权限吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.get('/driver/roleMenu/delete/menu', {
          params: {
            roleId: role.id,
            menuId: menuId
          }
        }).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            role.menus = res.data.data
          } else {
            this.$message.error(res.data.message)
          }
        }).catch(err => {
          console.log(err)
          this.$message.error(err.message)
        })
      })
    },

    // 展示编辑角色的对话框
    showEditDialog(role){
      this.editForm = {...role};
      this.editDialogVisible = true
    },

    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },

    // 修改角色
    editRoleInfo(){
      this.$http.post("/driver/role/update", this.editForm).then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.editDialogVisible = false
          this.getRoleList()
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        console.log(err)
        this.$message.error(err.message)
      })
    },

    // 删除角色
    deleteRole(roleId){
      this.$confirm('确定删除该角色？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.get("/driver/role/delete", {
          params: {
            roleId: roleId
          }
        }).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.getRoleList()
          } else {
            this.$message.error(res.data.message)
          }
        }).catch(err => {
          console.log(err)
          this.$message.error(err.message)
        })
      })
    },

    // 展示分配权限的对话框
    setMenu(role) {
      this.roleId = role.id
      this.$http.get("/driver/menu/menuAll").then(res => {
        if (res.data.code === 200) {

          // 把获取到的权限数据保存到 data 中
          this.menusList = res.data.data

          // 递归获取三级节点的id
          this.getLeafKeys(role, this.defKeys)

          this.setMenuDialogVisible = true
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        console.log(err)
        this.$message.error(err.message)
      })
    },

    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getLeafKeys(node, arr) {

      if (!node.children) {
        node.menus.forEach(item => this.getLeafKeys(item, arr))
        return
      }

      // 如果当前 node 节点的 children 为空，则是三级节点
      if (node.children.length === 0) {
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getLeafKeys(item, arr))
    },

    // 监听分配权限对话框的关闭事件
    setMenuDialogClosed() {
      this.defKeys = []
    },

    // 为角色分配权限
    allotMenus(){
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      this.$http.post("/driver/roleMenu/allotMenus", {
        roleId: this.roleId,
        menusId: keys
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.getRoleList()
          this.setMenuDialogVisible = false
        }else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        this.$message.error(err.message)
      })
    }
  }
}
</script>

<style lang="less" scoped>

.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
